package cn.bdqn.controller;

import cn.bdqn.entity.User;
import cn.bdqn.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Resource
    UserService userService;

    /**
     * 跳转登录页面
     * @return
     */
    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    /**
     * 跳转首页
     * @return
     */
    @RequestMapping("/main")
    public String main(){
        return "main";
    }

    /**
     * 登录
     * @param usrName
     * @param usrPassword
     * @param model
     * @param session
     * @return
     */
    @RequestMapping(value="/dologin")
    public String dologin(String usrName, String usrPassword,
                        Model model, HttpSession session){
        //调用service方法，进行用户匹配
        User user = userService.login(usrName, usrPassword);
        if(user != null){//登录成功
            //放入session
            session.setAttribute("loginUser", user);
            //重定向到main方法
            return "redirect:/main";
        }else{
            //页面跳转（login.html）带提示信息--转发
            model.addAttribute("msg", "用户名或密码不正确");
            //转发到login.html
            return "redirect:/login";
        }
    }

    /**
     * 退出
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("loginUser");
        return "login";
    }
}
